package com.cychat.mall.controller;

import com.Cychat.commons.entity.ResultMessage;
import com.Cychat.commons.entity.pojo.Product;
import com.Cychat.commons.entity.pojo.ShoppingCart;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cychat.mall.entity.DTO.ShoppingCartDTO;
import com.cychat.mall.entity.DTO.UpdateCartQuantitiesRequest;
import com.cychat.mall.service.ProductService;
import com.cychat.mall.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-11-2:下午 2:59  <br/>
 * Description: 购物车控制器
 */
@RestController
@RequestMapping("/api/mall")
@CrossOrigin
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private ProductService productService;
    //根据用户ID查询购物车中的商品
    @GetMapping("/shoppingCart/list/{userId}")
    public ResultMessage<List<ShoppingCartDTO>> getShoppingCartByUserId(@PathVariable("userId") Long userId){
        try {
            if (userId == null || userId <= 0) {
                return ResultMessage.error("用户ID无效");
            }

            LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShoppingCart::getUserId, userId);
            List<ShoppingCart> cartList = shoppingCartService.list(wrapper);

            if (cartList.isEmpty()) {
                return ResultMessage.success(new ArrayList<>());
            }

            // 提取所有商品ID，去重后批量查询商品信息
            List<Integer> productIds = cartList.stream()
                    .map(ShoppingCart::getProductId)
                    .distinct() // 建议加 distinct 避免重复查询
                    .collect(Collectors.toList());
            List<Product> productList = productService.listByIds(productIds);

            // 构建商品ID到Product的映射
            Map<Integer, Product> productMap = productList.stream()
                    .collect(Collectors.toMap(Product::getProductId, p -> p, (p1, p2) -> p1));

            // 转换为 ShoppingCartDTO 并填充商品信息
            List<ShoppingCartDTO> dtoList = cartList.stream().map(cart -> {
                ShoppingCartDTO dto = new ShoppingCartDTO();
                dto.setCartId(cart.getCartId());
                dto.setUserId(cart.getUserId());
                dto.setProductId(cart.getProductId());
                dto.setQuantity(cart.getQuantity());
                dto.setSelected(cart.getSelected());
                dto.setCreateTime(cart.getCreateTime());
                dto.setUpdateTime(cart.getUpdateTime());
                dto.setProduct(productMap.get(cart.getProductId()));
                return dto;
            }).collect(Collectors.toList());

            return ResultMessage.success(dtoList);

        } catch (Exception e) {
            e.printStackTrace(); // 生产环境建议用日志框架如 log.error()
            return ResultMessage.error("查询购物车失败: " + e.getMessage());
        }
    }
    //根据用户ID更新购物车中的商品数量
    @PostMapping("/shoppingCart/updateQuantity/{userId}")
    public ResultMessage<String> updateCartQuantities(
            @PathVariable("userId") Long userId,
            @RequestBody UpdateCartQuantitiesRequest request) {
        if (userId == null || userId <= 0) {
            return ResultMessage.error("用户ID无效");
        }
        if (request.getItems() == null || request.getItems().isEmpty()) {
            return ResultMessage.error("更新列表不能为空");
        }
        try {
            shoppingCartService.updateCartQuantities(userId, request);
            return ResultMessage.success("购物车数量更新成功");
        } catch (Exception e) {
            return ResultMessage.error(e.getMessage());
        }
    }

    //根据userId和cartIds删除购物车中的商品
    @DeleteMapping("/shoppingCart/delete/{userId}")
    public ResultMessage<String> deleteCartItems(
            @PathVariable("userId") Long userId,
            @RequestBody List<Integer> cartIds) {
        if (userId == null || userId <= 0) {
            return ResultMessage.error("用户ID无效");
        }
        if (cartIds == null || cartIds.isEmpty()) {
            return ResultMessage.error("购物车ID列表不能为空");
        }
        try {
            shoppingCartService.deleteCartItems(userId, cartIds);
            return ResultMessage.success("购物车商品删除成功");
        } catch (Exception e) {
            return ResultMessage.error(e.getMessage());
        }
    }


}
